<template>
  <div class="app-container">
    <div class="d-flex justify-space-between align-center">
      <span>{{ pageType === 'add' ? '新增渠道' : '编辑渠道' }}</span>
      <el-button type="primary" plain @click="$router.go(-1)">返回</el-button>
    </div>
    <div class="d-flex justify-center align-center mt-50">
      <el-form
        ref="form"
        :rules="rules"
        :model="form"
        label-width="120px"
        style="width: 500px"
      >
        <el-form-item label="渠道名称：" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入渠道名称" />
        </el-form-item>
        <el-form-item label="渠道公司名称：" prop="company">
          <el-input v-model="form.company" placeholder="请输入渠道公司名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSave">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { addChannel, updateChannel } from '@/api/channel/index'
export default {
  name: 'ChannelCreate',
  data() {
    return {
      form: {
        nickname: '',
        company: ''
      },
      rules: {
        nickname: [
          { required: true, message: '请输入渠道名称', trigger: 'blur' }
        ],
        company: [
          { required: true, message: '请输入渠道公司名称名称', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    pageType() {
      return this.$route.params.type
    }
  },
  created() {
    if (this.pageType !== 'add') {
      const { id, nickname, company } = this.$route.params
      this.form.id = id
      this.form.nickname = nickname
      this.form.company = company
    }
    console.log(this.$route)
  },
  methods: {
    async onSave() {
      try {
        await this.$refs['form'].validate()
        this.pageType === 'add' ? this.addChannel() : this.updateChannel()
      } catch (error) {}
    },
    async addChannel() {
      const { code } = await addChannel(this.form)
      if (code === 200) {
        this.$message.success('新增渠道成功')
        this.$router.go(-1)
      }
    },
    async updateChannel() {
      const { code } = await updateChannel(this.form)
      if (code === 200) {
        this.$message.success('编辑渠道成功')
        this.$router.go(-1)
      }
    }
  }
}
</script>
